package com.naiterui.ehp.bs.pharmacist.service.security.impl;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.naiterui.common.redis.RedisUtil;
import com.naiterui.ehp.bp.support.exception.PublicService;
import com.naiterui.ehp.bp.support.utils.JsonMapper;
import com.naiterui.ehp.bs.pharmacist.entity.Pharmacist;
import com.naiterui.ehp.bs.pharmacist.exception.ExceptionCodes;
import com.naiterui.ehp.bs.pharmacist.repository.mysql.PharmacistRepository;
import com.naiterui.ehp.bs.pharmacist.service.security.ISecurityService;
import com.naiterui.ehp.bs.pharmacist.utils.Constants;

@Service
public class PharmacistSecurityServiceImpl implements ISecurityService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PharmacistSecurityServiceImpl.class);

    @Autowired
    private PharmacistRepository repository;

    @Override
    public boolean saveCheckToken(Long pharmacistId, String token) throws IOException {

        return this.saveCheckToken(pharmacistId.toString(), token, null);
    }

    /*
     * 校验token-response写入异常信息
     * ISecurityService.saveCheckToken()
     */
    @Override
    public boolean saveCheckToken(String pharmacistId, String token, HttpServletResponse response) throws IOException {

        if (!StringUtils.isNumeric(pharmacistId) || StringUtils.isBlank(token)) {
            this.stuffErrorCode(response, ExceptionCodes.TOLOGIN);
            return false;
        }

        try {
            String loginCacheKey = Constants.PHARMACIST_LOGIN_TOKEN_KEY + pharmacistId;
            String cacheToken = RedisUtil.valueOps().getString(loginCacheKey);
            if (token.equals(cacheToken)) {
                return true;
            }

        } catch (Exception e) {

            LOGGER.error("从redis中获取缓存用户登陆token失败,pharmacistId=" + pharmacistId, e);
        }

        // 数据库登录校验

        Pharmacist pharmacist = this.repository.get(Long.parseLong(pharmacistId));
        if (pharmacist == null) {
            // 提示去登陆
            this.stuffErrorCode(response, ExceptionCodes.TOLOGIN);
            return false;
        }

        if (pharmacist.getStatus().equals(Pharmacist.STATUS_NOT_ACTIVE)) {
            // 提示用户未注册
            this.stuffErrorCode(response, ExceptionCodes.PHARMACIST_ACCOUNT_NOT_NORMAL);
            return false;
        }

        if (!token.equals(pharmacist.getToken())) {
            // 提示去登陆
            this.stuffErrorCode(response, ExceptionCodes.TOLOGIN);
            return false;
        }

        try {
            String cacheKey = Constants.PHARMACIST_LOGIN_TOKEN_KEY + pharmacistId;
            RedisUtil.valueOps().set(cacheKey, token);
        } catch (Exception e) {

            LOGGER.error("向redis中缓存用户登陆token失败,pharmacistId=" + pharmacistId, e);
        }

        return true;
    }

    /**
     * SecurityServiceImpl.stuffErrorCode()
     *
     * @param response
     * @param errorCode
     *
     * @throws IOException
     * @Author mudou
     * @Date 2017年7月10日
     * @since 2.8.0
     */
    private void stuffErrorCode(HttpServletResponse response, int errorCode) throws IOException {
        if (null == response) {
            return;
        }
        response.getWriter().println(JsonMapper.toJson(PublicService.returnResponseVO(errorCode)));
    }

}
